<template>
  <div class="purchase-order-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>采购订单管理</h2>
    </div>



    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="left-actions">
        <el-button type="primary" @click="handleAdd" icon="Plus">
          新增
        </el-button>
        <el-button type="success" @click="handleExportExcel" icon="Document">
          导出Excel
        </el-button>
        <el-button type="warning" @click="handleExportPdf" icon="Printer">
          导出PDF
        </el-button>
        <el-button type="info" @click="testApi" icon="Connection">
          测试API
        </el-button>
        <el-button type="warning" @click="insertTestData" icon="DataAnalysis">
          插入测试数据
        </el-button>
        <el-button type="primary" @click="goToIncomingInspection" icon="Finished">
          到货检验
        </el-button>
      </div>
      <div class="right-actions">
        <el-input
          v-model="searchText"
          placeholder="请搜索"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" icon="Search" />
          </template>
        </el-input>
        <el-button @click="handleRefresh" icon="Refresh" />
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="purchaseOrders"
      v-loading="loading"
      stripe
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" width="60" />
      <el-table-column prop="purchaseOrderNumber" label="采购编码" width="180" />
      <el-table-column prop="orderSubject" label="采购订单主题" min-width="200" />
      <el-table-column label="供应商名称" min-width="150">
        <template #default="scope">
          {{ scope.row.supplierName || '未知供应商' }}
        </template>
      </el-table-column>
      <el-table-column prop="purchaseDate" label="采购日期" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.purchaseDate) }}
        </template>
      </el-table-column>
      <el-table-column label="物品概要" min-width="150">
        <template #default="scope">
          <el-tooltip
            :content="getItemSummary(scope.row.details)"
            placement="top"
            :show-after="500"
          >
            <span>{{ getItemSummary(scope.row.details) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="采购部门" width="120">
        <template #default="scope">
          {{ scope.row.purchasingDepartmentName || '未知部门' }}
        </template>
      </el-table-column>
      <el-table-column label="采购人员" width="100">
        <template #default="scope">
          {{ scope.row.purchaserName || '未知人员' }}
        </template>
      </el-table-column>
      <el-table-column prop="totalAmountIncludingTax" label="总金额" width="100">
        <template #default="scope">
          {{ formatCurrency(scope.row.totalAmountIncludingTax) }}
        </template>
      </el-table-column>
      <el-table-column label="已付金额" width="100">
        <template #default="scope">
          {{ formatCurrency(0) }}
        </template>
      </el-table-column>
      <el-table-column label="已到票金额" width="120">
        <template #default="scope">
          {{ formatCurrency(0) }}
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="审批" width="80">
        <template #default="scope">
          <el-tag :type="getApprovalStatusType(scope.row.orderStatus)">
            {{ scope.row.orderStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="handleView(scope.row)"
          >
            查看
          </el-button>
          <el-button
            v-if="scope.row.orderStatus === '草稿'"
            type="warning"
            link
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.orderStatus === '草稿'"
            type="danger"
            link
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="pagination-info">
        共 {{ totalCount }} 项数据
      </div>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <PurchaseOrderForm
      v-model:visible="formVisible"
      :purchase-order="currentPurchaseOrder"
      :is-edit="isEdit"
      @success="handleFormSuccess"
    />

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="400px"
    >
      <p>确定要删除采购订单 "{{ currentPurchaseOrder?.orderSubject }}" 吗？</p>
      <p class="text-danger">删除后无法恢复！</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { purchaseOrderApi } from '@/api/purchaseOrderApi'
import type {
  PurchaseOrderDto,
  GetPurchaseOrderListQuery
} from '@/types/purchaseOrder'
import PurchaseOrderForm from './PurchaseOrderForm.vue'
import * as XLSX from 'xlsx'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

// 路由
const router = useRouter()

// 响应式数据
const loading = ref(false)
const purchaseOrders = ref<PurchaseOrderDto[]>([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchText = ref('')
const selectedRows = ref<PurchaseOrderDto[]>([])
const formVisible = ref(false)
const isEdit = ref(false)
const currentPurchaseOrder = ref<PurchaseOrderDto | null>(null)
const deleteDialogVisible = ref(false)
const lastError = ref<string | null>(null)

// 查询参数
const queryParams = reactive<GetPurchaseOrderListQuery>({
  pageIndex: 1,
  pageSize: 10,
  orderSubject: '',
  purchaseOrderNumber: '',
  supplierId: undefined,
  orderStatus: undefined,
  purchaseDateStart: undefined,
  purchaseDateEnd: undefined,
  createdBy: undefined
})

// 计算属性
const hasSelectedRows = computed(() => selectedRows.value.length > 0)

// 生命周期
onMounted(() => {
  loadPurchaseOrders()
})

// 方法
const loadPurchaseOrders = async () => {
  try {
    loading.value = true
    queryParams.pageIndex = currentPage.value
    queryParams.pageSize = pageSize.value
    queryParams.orderSubject = searchText.value

    console.log('开始加载采购订单列表，参数:', queryParams)
    console.log('API基础URL:', 'http://localhost:5000')
    
    // 使用API服务调用
    const response = await purchaseOrderApi.getPurchaseOrderList(queryParams)
    console.log('API响应:', response)
    
    if (response.code === 200) {
      console.log('响应数据:', response.data)
      purchaseOrders.value = response.data.pageData || []
      totalCount.value = response.data.totalCount || 0
      console.log('设置到组件的数据:', { 
        purchaseOrders: purchaseOrders.value, 
        totalCount: totalCount.value 
      })
      
      // 如果没有数据，显示提示信息
      if (purchaseOrders.value.length === 0) {
        console.log('没有找到采购订单数据，可能原因：')
        console.log('1. 数据库中没有测试数据')
        console.log('2. 查询条件过于严格')
        console.log('3. 数据库连接问题')
        ElMessage.info('暂无采购订单数据，请先添加测试数据')
      }
    } else {
      console.error('API返回错误:', response.message)
      ElMessage.error(response.message || '获取采购订单列表失败')
    }
  } catch (error) {
    console.error('加载采购订单列表失败:', error)
    console.error('错误详情:', {
      name: error.name,
      message: error.message,
      stack: error.stack
    })
    lastError.value = error.message
    ElMessage.error(`加载采购订单列表失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadPurchaseOrders()
}

const handleRefresh = () => {
  loadPurchaseOrders()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadPurchaseOrders()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadPurchaseOrders()
}

const handleSelectionChange = (rows: PurchaseOrderDto[]) => {
  selectedRows.value = rows
}

const handleAdd = () => {
  isEdit.value = false
  currentPurchaseOrder.value = null
  formVisible.value = true
}

const handleEdit = (row: PurchaseOrderDto) => {
  isEdit.value = true
  currentPurchaseOrder.value = { ...row }
  formVisible.value = true
}

const handleView = (row: PurchaseOrderDto) => {
  router.push(`/PurchaseOrderDetail/${row.id}`)
}

const handleDelete = (row: PurchaseOrderDto) => {
  currentPurchaseOrder.value = row
  deleteDialogVisible.value = true
}

const confirmDelete = async () => {
  if (!currentPurchaseOrder.value) return

  try {
    const response = await fetch(`http://localhost:5000/api/PurchaseOrder/${currentPurchaseOrder.value.id}`, {
      method: 'DELETE'
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const data = await response.json()
    
    if (data.code === 200) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      loadPurchaseOrders()
    } else {
      ElMessage.error(data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除采购订单失败:', error)
    lastError.value = error.message
    ElMessage.error(`删除采购订单失败: ${error.message}`)
  }
}

const handleFormSuccess = () => {
  formVisible.value = false
  loadPurchaseOrders()
  ElMessage.success('操作成功')
}

const normalizeRowsForExport = () => {
  const rows = selectedRows.value.length > 0 ? selectedRows.value : purchaseOrders.value
  return rows.map((r, idx) => ({
    序号: idx + 1,
    采购编码: r.purchaseOrderNumber || '',
    采购订单主题: r.orderSubject || '',
    供应商名称: r.supplierName || '',
    采购日期: formatDate(r.purchaseDate) || '',
    物品概要: getItemSummary((r as any).details || []),
    采购部门: r.purchasingDepartmentName || '',
    采购人员: r.purchaserName || '',
    总金额含税: r.totalAmountIncludingTax ?? 0
  }))
}

const handleExportExcel = () => {
  const data = normalizeRowsForExport()
  if (data.length === 0) {
    ElMessage.info('没有可导出的数据')
    return
  }
  const ws = XLSX.utils.json_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '采购订单')
  const ts = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')
  XLSX.writeFile(wb, `采购订单列表-${ts}.xlsx`)
  ElMessage.success('Excel 导出成功')
}

const handleExportPdf = async () => {
  const table = document.querySelector('.purchase-order-list') as HTMLElement
  if (!table) {
    ElMessage.error('未找到可导出的区域')
    return
  }
  try {
    const canvas = await html2canvas(table, { scale: 2, useCORS: true, backgroundColor: '#ffffff' })
    const imgData = canvas.toDataURL('image/png')
    const pdf = new jsPDF('l', 'pt', 'a4')
    const pageWidth = pdf.internal.pageSize.getWidth()
    const pageHeight = pdf.internal.pageSize.getHeight()

    const imgWidth = pageWidth - 40
    const imgHeight = (canvas.height * imgWidth) / canvas.width

    let y = 20
    pdf.addImage(imgData, 'PNG', 20, y, imgWidth, imgHeight)
    pdf.setFontSize(10)
    pdf.text(`导出时间: ${new Date().toLocaleString()}`, 20, pageHeight - 10)

    const ts = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')
    pdf.save(`采购订单列表-${ts}.pdf`)
    ElMessage.success('PDF 导出成功')
  } catch (e) {
    console.error('导出 PDF 失败', e)
    ElMessage.error('导出 PDF 失败')
  }
}

const goToIncomingInspection = () => {
  router.push('/IncomingInspectionList')
}

const testApi = async () => {
  try {
    loading.value = true
    const response = await purchaseOrderApi.getPurchaseOrderList({
      pageIndex: 1,
      pageSize: 10,
      orderSubject: '测试',
      purchaseOrderNumber: '',
      supplierId: undefined,
      orderStatus: undefined,
      purchaseDateStart: undefined,
      purchaseDateEnd: undefined,
      createdBy: undefined
    })
    console.log('测试API响应:', response)
    if (response.code === 200) {
      ElMessage.success('测试API成功')
      purchaseOrders.value = response.data.pageData || []
      totalCount.value = response.data.totalCount || 0
    } else {
      ElMessage.error(response.message || '测试API失败')
    }
  } catch (error) {
    console.error('测试API失败:', error)
    ElMessage.error('测试API失败')
  } finally {
    loading.value = false
  }
}

const insertTestData = async () => {
  try {
    loading.value = true
    const response = await purchaseOrderApi.insertTestData()
    console.log('插入测试数据响应:', response)
    if (response.code === 200) {
      ElMessage.success('插入测试数据成功')
      loadPurchaseOrders() // 刷新列表以显示新数据
    } else {
      ElMessage.error(response.message || '插入测试数据失败')
    }
  } catch (error) {
    console.error('插入测试数据失败:', error)
    lastError.value = error.message
    ElMessage.error(`插入测试数据失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 工具方法
const formatCurrency = (amount: number | null | undefined) => {
  if (amount === null || amount === undefined || isNaN(amount)) return '¥0.00'
  try {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY'
    }).format(amount)
  } catch (error) {
    console.error('格式化金额时出错:', error)
    return '¥0.00'
  }
}

const getApprovalStatusType = (status: string | null | undefined) => {
  if (!status) return 'info'
  
  try {
    switch (status) {
      case '已审批':
      case '已完成':
        return 'success'
      case '待审批':
        return 'warning'
      case '驳回':
        return 'danger'
      case '审批中':
        return 'info'
      case '草稿':
        return 'info'
      default:
        return 'info'
    }
  } catch (error) {
    console.error('获取审批状态类型时出错:', error)
    return 'info'
  }
}

const getItemSummary = (details: any[]) => {
  if (!details || details.length === 0) return '无明细'
  
  try {
    const summary = details.slice(0, 3).map(item => {
      const itemName = item?.itemName || '未知物品'
      const quantity = item?.purchaseQuantity || 0
      return `${itemName}: ${quantity}`
    }).join(', ')
    
    if (details.length > 3) {
      return `${summary} 等${details.length}项`
    }
    return summary
  } catch (error) {
    console.error('处理物品概要时出错:', error)
    return '无明细'
  }
}

const formatDate = (date: string | Date | null | undefined) => {
  if (!date) return '-'
  try {
    const dateObj = typeof date === 'string' ? new Date(date) : date
    if (isNaN(dateObj.getTime())) return '-'
    return dateObj.toLocaleDateString('zh-CN')
  } catch (error) {
    console.error('格式化日期时出错:', error)
    return '-'
  }
}

// 获取API基础URL (用于测试)
const getApiUrl = () => {
  return 'http://localhost:5000'
}

// 直接测试Fetch (用于调试)
const testDirectFetch = async () => {
  try {
    loading.value = true
    console.log('开始直接测试Fetch...')
    
    const response = await fetch('http://localhost:5000/api/PurchaseOrder/list?PageIndex=1&PageSize=10')
    console.log('Fetch响应状态:', response.status)
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const data = await response.json()
    console.log('Fetch响应数据:', data)
    
    if (data.code === 200) {
      ElMessage.success('直接Fetch成功')
      purchaseOrders.value = data.data.pageData || []
      totalCount.value = data.data.totalCount || 0
    } else {
      ElMessage.error(data.message || '直接Fetch失败')
    }
  } catch (error) {
    console.error('直接Fetch失败:', error)
    lastError.value = error.message
    ElMessage.error(`直接Fetch失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 测试API调用 (用于调试)
const testApiCall = async () => {
  try {
    loading.value = true
    console.log('开始测试API调用...')
    
    const response = await fetch('http://localhost:5000/api/PurchaseOrder/list?PageIndex=1&PageSize=10&OrderSubject=测试')
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const data = await response.json()
    console.log('测试API响应:', data)
    
    if (data.code === 200) {
      ElMessage.success('测试API成功')
      purchaseOrders.value = data.data.pageData || []
      totalCount.value = data.data.totalCount || 0
    } else {
      ElMessage.error(data.message || '测试API失败')
    }
  } catch (error) {
    console.error('测试API失败:', error)
    lastError.value = error.message
    ElMessage.error(`测试API失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.purchase-order-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
}

.left-actions {
  display: flex;
  gap: 10px;
}

.right-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.text-danger {
  color: #f56c6c;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 